package com.songshuai.webapi.permission.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.songshuai.webapi.baseapi.constant.BaseConstant;
import com.songshuai.webapi.baseapi.dto.UserBaseInfoDto;
import com.songshuai.webapi.baseapi.dto.feign.request.NavigationReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.UserAddReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.UserInfoUpdateReqDto;
import com.songshuai.webapi.baseapi.enumerations.PositionEnum;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.dto.feign.response.AccountInfoResDto;
import com.songshuai.webapi.baseapi.dto.feign.response.AccountPageLIstResDto;
import com.songshuai.webapi.baseapi.dto.feign.response.NavAndFuncByRoleResDto;
import com.songshuai.webapi.baseapi.dto.feign.response.AccountInfoListResDto;
import com.songshuai.webapi.baseapi.utils.EncryptUtil;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.baseapi.utils.RegexUtil;
import com.songshuai.webapi.permission.Util.PageUtil;
import com.songshuai.webapi.permission.Util.Util;
import com.songshuai.webapi.permission.common.enumerations.DepartmentButtonType;
import com.songshuai.webapi.permission.common.enumerations.UserLevelType;
import com.songshuai.webapi.permission.common.enumerations.UserType;
import com.songshuai.webapi.permission.common.enumerations.error.DepartmentError;
import com.songshuai.webapi.permission.constant.UserConstant;
import com.songshuai.webapi.permission.dao.*;
import com.songshuai.webapi.permission.dao.custom.UsersMapper;
import com.songshuai.webapi.permission.dto.po.RolesLoginPojo;
import com.songshuai.webapi.permission.dto.po.UserHasPermissionPojo;
import com.songshuai.webapi.permission.dto.po.UsersResPojo;
import com.songshuai.webapi.permission.dto.request.Departments.*;
import com.songshuai.webapi.permission.dto.request.*;
import com.songshuai.webapi.permission.dto.response.*;
import com.songshuai.webapi.permission.model.*;
import com.songshuai.webapi.permission.service.CurrentUserService;
import com.songshuai.webapi.permission.service.FunctionsService;
import com.songshuai.webapi.permission.service.NavigationsService;
import com.songshuai.webapi.permission.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private NavigationsService navigationsService;

    @Autowired
    private YxUsersMapper usersMapper;

    @Autowired
    private YxUserNavigationsMapper userNavigationsMapper;

    @Autowired
    private YxUserNavigationFunctionMapper userNavigationFunctionMapper;

    @Autowired
    private UsersMapper usersExampleMapper;

    @Autowired
    private YxDepartmentUserMapper yxDepartmentUserMapper;

    @Autowired
    private YxUserAliyunmqMapper yxUserAliyunmqMapper;

    @Autowired
    private YxDepartmentsMapper yxDepartmentsMapper;

    @Autowired
    private FunctionsService functionsService;

    @Autowired
    private CurrentUserService currentUserService;

    @Autowired
    private YxDepartmentsMapper departmentsMapper;

    @Autowired
    private YxDepartmentLeaderMapper yxDepartmentLeaderMapper;


    //返回用户所有角色
    private List<UsersResDto> getUserRoles(List<UsersResDto> lists){


        if (lists == null || lists.size() == 0) {
            return null;
        }

        List<Integer> arr = new ArrayList<Integer>();
        for(UsersResDto usersResDto:lists){
            arr.add(Integer.parseInt(usersResDto.getUserId()));
        }


        UserRolesReqDto userRolesReqDto = new UserRolesReqDto();
        userRolesReqDto.setUserIds(arr);
        List<UsersResDto> usersResDtos = yxDepartmentUserMapper.selectUserRoles(userRolesReqDto);

       return usersResDtos;
    }

    //用户角色字符组装
    private String getUserRolesMergeStr(String userId, List<UsersResDto> usersResDtos){

        if(usersResDtos == null || usersResDtos.size() == 0){
            return "";
        }

        StringBuffer sf = new StringBuffer();
        for(UsersResDto usersResDto:usersResDtos){
            if(userId.equals(usersResDto.getUserId())){
                sf.append(","+usersResDto.getRoleName());
            }
        }
        if(Util.IsNullAndEmpty(sf.toString())){
            return "";
        }
        return sf.toString().substring(1);
    }


    //查找本部门下所有主子部门（包含自身）--mysql版
    private List<Integer> findSubDepartment(Integer departmentId){

        List<Integer> all = new ArrayList<Integer>();
        String str = yxDepartmentUserMapper.selectSubDepartmentSql(departmentId);
        if(Util.IsNullAndEmpty(str)){
            return all;
        }
        str = str.substring(1);
        String[] allStr = str.split(",");
        for(String s:allStr){
            all.add(Integer.parseInt(s));
        }
        return all;
    }

    //查找本部门下所有主子部门（包含自身）---- mybatis版
    private List<Integer> findSubDepartmentForSql(Integer departmentId){

        List<Integer> all = new ArrayList<Integer>();
        all.add(departmentId);

        List<Integer> ids = yxDepartmentUserMapper.selectSubDepartment(departmentId);

        if(ids != null && ids.size() > 0){
            for(Integer id:ids){
                all.addAll(findSubDepartment(id));
            }

        }
        return all;
    }


    /**
     * 设置部门领导
     */
    @Transactional
    public void updateDepartmentsLeader(UpdateDepartmentsLeaderReqDto updateDepartmentsLeaderReqDto){

        updateDepartmentsLeaderReqDto.setEditorId(currentUserService.getUserId());
        //参数校验
        if(updateDepartmentsLeaderReqDto.getDepartmentId() == null){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        if(yxDepartmentsMapper.selectByDepartmentId(updateDepartmentsLeaderReqDto.getDepartmentId()) == null){
            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }

        //清空部门领导
        if(Util.IsNullAndEmpty(updateDepartmentsLeaderReqDto.getLeaderIds())){
            //删除部门领导
            yxDepartmentUserMapper.deleteDepartmentLeader(updateDepartmentsLeaderReqDto.getDepartmentId());
            return;
        }

        String[] userIds = updateDepartmentsLeaderReqDto.getLeaderIds().split(",");

        if(userIds == null || userIds.length == 0){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        //校验非该部门人员不可设置部门领导
        for (String uid : userIds) {
            YxDepartmentUser ydu = new YxDepartmentUser();
            ydu.setUserId(Integer.parseInt(uid));
            ydu.setDepartmentId(updateDepartmentsLeaderReqDto.getDepartmentId());
            List<YxDepartmentUser> result = yxDepartmentUserMapper.selectByEntityList(ydu);
            if (result == null || result.size() == 0) {
                YxUsers yxUsers =  usersMapper.selectByPrimaryKey(Integer.parseInt(uid));
                throw new BusinessException(yxUsers.getTrueName()+":"+DepartmentError.ERROR_DEPARTMENT_RELATION_IS_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
            }
        }


        try {

            //删除部门领导
            yxDepartmentUserMapper.deleteDepartmentLeader(updateDepartmentsLeaderReqDto.getDepartmentId());
            //插入部门领导
            UpdateDepartmentsLeaderReqDto udl = null;

            for (String uid : userIds) {

                //设置领导
                udl = new UpdateDepartmentsLeaderReqDto();
                udl.setUserId(Integer.parseInt(uid));
                udl.setDepartmentId(updateDepartmentsLeaderReqDto.getDepartmentId());
                udl.setEditorId(updateDepartmentsLeaderReqDto.getEditorId());
                yxDepartmentUserMapper.updateDepartmentsLeader(udl);
            }

        }catch (Exception e){
            log.error("api/departments/updateDepartmentsLeader", e);
            throw new BusinessException(ResultStatus.ERROR_UPDATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }

    }

    //设置部门领导-人员列表
    public List<UsersResPojo> updateDepartmentsLeaderUserList(UpdateDepartmentsLeaderUserListReqDto updateDepartmentsLeaderUserListReqDto){

        //参数校验
        if(updateDepartmentsLeaderUserListReqDto.getDepartmentId() == null){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        if(yxDepartmentsMapper.selectByDepartmentId(updateDepartmentsLeaderUserListReqDto.getDepartmentId()) == null){
            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }

        updateDepartmentsLeaderUserListReqDto.setEditorId(currentUserService.getUserId());
        try {
            //如果是超级管理员，显示所有用户
            boolean isSuperAdmin = currentUserService.CheckIsSysAdmin();
            if(isSuperAdmin){
                AllUsersReqDto allUsersReqDto = new AllUsersReqDto();
                allUsersReqDto.setKeyword(updateDepartmentsLeaderUserListReqDto.getKeyword());
                allUsersReqDto.setDepartmentId(updateDepartmentsLeaderUserListReqDto.getDepartmentId());
                allUsersReqDto.setFunctionMode(DepartmentButtonType.THREE.getCode());
                return this.getAllUsers(allUsersReqDto);
            }
            return yxDepartmentUserMapper.selectDepartmentsLeaderUserList(updateDepartmentsLeaderUserListReqDto);

        }catch (Exception e){
            log.error("api/departments/updateDepartmentsLeaderUserList", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }
    }

    //设置部门领导-回填人员列表
    public List<UsersResPojo> updateDepartmentsLeaderBackUserList(UpdateDepartmentsLeaderBackUserListReqDto updateDepartmentsLeaderBackUserListReqDto){
        //参数校验
        if(updateDepartmentsLeaderBackUserListReqDto.getDepartmentId() == null){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        if(yxDepartmentsMapper.selectByDepartmentId(updateDepartmentsLeaderBackUserListReqDto.getDepartmentId()) == null){
            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }

        try{
            return yxDepartmentUserMapper.updateDepartmentsLeaderBackUserList(updateDepartmentsLeaderBackUserListReqDto);
        }catch (Exception e){
            log.error("api/departments/updateDepartmentsLeaderBackUserList", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }
    }

    /*
        所有用户列表
     */
    private List<UsersResPojo> getAllUsers(AllUsersReqDto allUsersReqDto){

        return yxDepartmentUserMapper.getAllUsers(allUsersReqDto);
    }

    //查找部门列表(当前用户所属部门，自己是领导的部门)
    private List<Integer> getLeaderDepartmentId(UpdateUserDepartmentUserListReqDto updateUserDepartmentUserListReqDto){

        List<Integer> all = new ArrayList<Integer>();

        //查找部门列表(当前用户所属部门，自己是领导的部门)
        List<YxDepartments> yxDepartmentsLists = yxDepartmentUserMapper.updateUserDepartmentUserListSub(updateUserDepartmentUserListReqDto);

        //查找部门主子列表
        for (YxDepartments yxDepartments : yxDepartmentsLists) {
            all.addAll(this.findSubDepartment(yxDepartments.getId()));
        }

        return all;

    }

    //调入已有用户/设置部门关系-人员列表
    public List<UsersResPojo> updateUserDepartmentUserList(UpdateUserDepartmentUserListReqDto updateUserDepartmentUserListReqDto){

        //参数校验
        if(updateUserDepartmentUserListReqDto.getDepartmentId() == null || updateUserDepartmentUserListReqDto.getFunctionMode() == null){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        if(yxDepartmentsMapper.selectByDepartmentId(updateUserDepartmentUserListReqDto.getDepartmentId()) == null){
            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }

        updateUserDepartmentUserListReqDto.setEditorId(currentUserService.getUserId());

        try {
            //如果是超级管理员，显示所有用户
            boolean isSuperAdmin = currentUserService.CheckIsSysAdmin();

            if(isSuperAdmin){
                AllUsersReqDto allUsersReqDto = new AllUsersReqDto();
                allUsersReqDto.setKeyword(updateUserDepartmentUserListReqDto.getKeyword());
                allUsersReqDto.setDepartmentId(updateUserDepartmentUserListReqDto.getDepartmentId());
                allUsersReqDto.setFunctionMode(updateUserDepartmentUserListReqDto.getFunctionMode());
                return this.getAllUsers(allUsersReqDto);
            }

            //查找包含自己的领导部门
            List<Integer> all = this.getLeaderDepartmentId(updateUserDepartmentUserListReqDto);

            if (all.size() == 0) {
                all.add(-1);
            }

            updateUserDepartmentUserListReqDto.setDepartmentIds(all);

            return yxDepartmentUserMapper.updateUserDepartmentUserList(updateUserDepartmentUserListReqDto);

        }catch (Exception e){
            log.error("api/departments/updateUserDepartmentUserList", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }
    }

    /*
    * 查找当前登录人级别
    * 1：超级管理员
    * 2：部门领导
    * 3；普通用户
    */
    private BaseParmDto<UserListReqDto> findUserLevel(BaseParmDto<UserListReqDto> request){

        //1.超级管理员
        boolean isSuperAdmin = currentUserService.CheckIsSysAdmin();
        if(isSuperAdmin){
           request.getParam().setUserLevel(UserLevelType.ADMIN.getCode());
           log.info("登录人身份：【管理员】");
           return request;
        }

        //2.部门领导
        UpdateUserDepartmentUserListReqDto updateUserDepartmentUserListReqDto = new UpdateUserDepartmentUserListReqDto();
        updateUserDepartmentUserListReqDto.setEditorId(request.getParam().getEditorId());
        List<Integer> all = this.getLeaderDepartmentId(updateUserDepartmentUserListReqDto);
        if(all.size() > 0){
            request.getParam().setUserLevel(UserLevelType.LEADER.getCode());
            request.getParam().setSelfDepartmentIds(all);
            log.info("登录人身份：【部门领导】");
            return request;
        }

        //3.普通用户
        request.getParam().setUserLevel(UserLevelType.CUSTOMER.getCode());
        log.info("登录人身份：【普通用户】");
        return request;
    }

    public List<YxUsers> queryUsersForStr(String ids){
        String[] userIds = ids.split(",");
        return yxDepartmentUserMapper.queryUsersForStr(userIds);
    }

    public PageUtil selectUsersForDeparent(BaseParmDto<UserListReqDto> request){

        request.getParam().setEditorId(currentUserService.getUserId());
        //参数校验
        if(request.getParam() == null ||request.getParam().getDepartmentId() == null || request.getParam().getIsAll() == null || request.getParam().getIsSort() == null || request.getParam().getSortColumn() == null){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        if(yxDepartmentsMapper.selectByDepartmentId(request.getParam().getDepartmentId()) == null){
            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }

        try {

            List<Integer> departmentAll = new ArrayList<Integer>();
            if (request.getParam().getIsAll() == 1) {
                //包含子部门的成员
                departmentAll = this.findSubDepartment(request.getParam().getDepartmentId());

            } else {
                //不包含子部门成员
                departmentAll.add(request.getParam().getDepartmentId());
            }
            request.getParam().setDepartmentIds(departmentAll);

            //设置登录身份
            request = this.findUserLevel(request);
            Integer count = yxDepartmentUserMapper.selectUsersForDeparentCount(request.getParam());

            //设置分页
            PageUtil page = new PageUtil(request.getPageIndex(), request.getPageSize(), count);
            request.getParam().setStart(page.getStart());
            request.getParam().setEnd(page.getEnd());

            List<UsersResDto> lists = yxDepartmentUserMapper.selectUsersForDeparent(request.getParam());
            //查询用户角色
            List<UsersResDto> allUserRoles = this.getUserRoles(lists);

            for (UsersResDto usersResDto : lists) {
                //角色拼接列表
                usersResDto.setRoleName(this.getUserRolesMergeStr(usersResDto.getUserId(), allUserRoles));
                //性别
                if (Integer.parseInt(usersResDto.getSex()) == UserType.Man.getCode()) {
                    usersResDto.setSex(UserType.Man.getMsg());
                } else if (Integer.parseInt(usersResDto.getSex()) == UserType.Woman.getCode()) {
                    usersResDto.setSex(UserType.Woman.getMsg());
                } else {
                    usersResDto.setSex(UserType.Unknown.getMsg());
                }

                //是否离职
                if (Integer.parseInt(usersResDto.getIsLeave()) == UserType.Isleave.getCode()) {
                    usersResDto.setIsLeave(UserType.Isleave.getMsg());
                } else {
                    usersResDto.setIsLeave(UserType.Noleave.getMsg());
                }

            }

            page.setLists(lists);
            return page;

        }catch (Exception e){
            log.error("api/departments/userList", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }

    }

    /**
     * 手机号与email校验
     */
    private void checkEmailAndMobile(AddDepartmentUserReqDto addDepartmentUserReqDto){

        //参数校验
        String email = addDepartmentUserReqDto.getEmail();
        String mobile = addDepartmentUserReqDto.getMobile();

        if(Util.IsNullAndEmpty(email) && Util.IsNullAndEmpty(mobile)){
            throw new BusinessException(DepartmentError.ERROR_EMAIL_AND_MOBILE_BOTH_NULL.getMsg(),ResultStatus.FAILOfficial);

        }

        if(!Util.IsNullAndEmpty(email)){

            if(!RegexUtil.isEmail(email)){
                throw new BusinessException(DepartmentError.ERROR_EMIAL_FORMAT.getMsg(), ResultStatus.FAILOfficial);

            }

            //检查email是否占用
            YxUsers yxUsers = new YxUsers();
            yxUsers.setEmail(email);
            if(yxDepartmentUserMapper.selectUsers(yxUsers)!=null){
                throw new BusinessException(DepartmentError.ERROR_EMAIL_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);

            }

        }

        if(!Util.IsNullAndEmpty(mobile)){

            if(!RegexUtil.isMobile(mobile)){
                throw new BusinessException(DepartmentError.ERROR_MOBILE_FORMAT.getMsg(), ResultStatus.FAILOfficial);

            }

            //检查手机是否占用
            YxUsers yxUsers = new YxUsers();
            yxUsers.setMobile(mobile);
            if(yxDepartmentUserMapper.selectUsers(yxUsers)!=null){
                throw new BusinessException(DepartmentError.ERROR_MOBILE_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);

            }
        }

    }


    @Transactional
    public void insertDepartmentUser(AddDepartmentUserReqDto addDepartmentUserReqDto){

        addDepartmentUserReqDto.setEditorId(currentUserService.getUserId());
        //参数校验
        if(addDepartmentUserReqDto.getDepartmentId() == null || Util.IsNullAndEmpty(addDepartmentUserReqDto.getUserName()) || Util.IsNullAndEmpty(addDepartmentUserReqDto.getWorkNo()) || Util.IsNullAndEmpty(addDepartmentUserReqDto.getTrueName())){

            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        //手机号和Email校验
        this.checkEmailAndMobile(addDepartmentUserReqDto);

        if(yxDepartmentsMapper.selectByDepartmentId(addDepartmentUserReqDto.getDepartmentId()) == null){

            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }

        //工号重复校验
        YxUsers yxUsers = new YxUsers();
        yxUsers.setWorkNo(addDepartmentUserReqDto.getWorkNo());
        if(yxDepartmentUserMapper.selectUsers(yxUsers)!=null){
            throw new BusinessException(DepartmentError.ERROR_WORK_NO_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        try{

            //插入用户
            //默认密码123456
            addDepartmentUserReqDto.setPassword(Util.md5("123456").substring(0,20).toUpperCase());
            Integer result1 = yxDepartmentUserMapper.insertUser(addDepartmentUserReqDto);

            //插入用户部门
            YxDepartmentUser yxDepartmentUser = new YxDepartmentUser();

            yxDepartmentUser.setUserId(addDepartmentUserReqDto.getUserId());
            yxDepartmentUser.setDepartmentId(addDepartmentUserReqDto.getDepartmentId());
            yxDepartmentUser.setCreateBy(addDepartmentUserReqDto.getEditorId());
            yxDepartmentUser.setCrmUserGroupId(0);
            yxDepartmentUser.setDepartRelation(Byte.valueOf("0"));
            Integer result2 = yxDepartmentUserMapper.insertDepartmentUser(yxDepartmentUser);


            //插入阿里云呼叫中心
            YxUserAliyunmq yxUserAliyunmq = new YxUserAliyunmq();
            yxUserAliyunmq.setUserId(addDepartmentUserReqDto.getUserId());
            yxUserAliyunmq.setIsDefault(addDepartmentUserReqDto.getAliyunmqIsDefault());
            yxUserAliyunmq.setMqId(addDepartmentUserReqDto.getMqId());
            yxUserAliyunmq.setMqUserId(addDepartmentUserReqDto.getMqUserId());
            yxUserAliyunmq.setMqAccount(addDepartmentUserReqDto.getMqAccount());
            yxUserAliyunmq.setMqPwd(addDepartmentUserReqDto.getMqPwd());
            yxUserAliyunmq.setMqGroupId(addDepartmentUserReqDto.getMqGroupId());
            yxUserAliyunmq.setMqPhone(addDepartmentUserReqDto.getMqPhone());
            yxUserAliyunmq.setMqExtension(addDepartmentUserReqDto.getMqExtension());
            yxUserAliyunmq.setCreateBy(addDepartmentUserReqDto.getEditorId());
            yxUserAliyunmq.setCreateTime(new Date());
            Integer result3 = yxUserAliyunmqMapper.insert(yxUserAliyunmq);

        }catch (Exception e) {
            log.error("api/departments/addDepartmentUser", e);
            throw new BusinessException(ResultStatus.ERROR_CREATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }

    }

    @Override
    public Map<String,Object> queryLoginNavAndFunc(Integer appId){
        Map<String,Object> result = new HashMap<>();
        //登录用户功能key
        List<FunctionsLoginResDto> funcList = functionsService.queryLoginFunctionList(appId);

        //登录用户菜单
        List<NavigationListResDto> navList = navigationsService.queryLoginNavigationList(appId);

        //登录用户功能-菜单
        List<NavAndFuncRelationResDto> navFuncList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(funcList)) {
            List<YxNavigationFunction> navigationFunctionList = usersMapper.queryNavFuncRelation(funcList);
            //类转换
            navFuncList = navigationFunctionList.stream().map(navigationFunction -> {
                NavAndFuncRelationResDto resDto = new NavAndFuncRelationResDto();
                PropertiesUtil.copyProperties(navigationFunction,resDto);
                return resDto;
            }).collect(Collectors.toList());
        }
        result.put("loginFuncList",funcList);
        result.put("loginNavList",navList);
        result.put("loginNavFuncList",navFuncList);
        YxUsers yxUsers = currentUserService.getUserBaseInfo();
        yxUsers.setPassword(null);
        result.put("loginUserBaseInfo",yxUsers);
        return result;
    }

    @Override
    public UserResDto queryUserById(Integer id){
        UserResDto resDto = new UserResDto();
        //用户阿里云信息
        YxUserAliyunmq yxUserAliyunmq = yxUserAliyunmqMapper.queryAliyunmqByUserId(id);
        if(yxUserAliyunmq != null) {
            PropertiesUtil.copyProperties(yxUserAliyunmq, resDto);
            resDto.setAliyunmqIsDefault(yxUserAliyunmq.getIsDefault() == 1);
            resDto.setAliyunmqId(yxUserAliyunmq.getId());
        }
        //用户基础信息
        YxUsers entity = usersMapper.queryUserById(id);
        if(entity != null) {
            PropertiesUtil.copyProperties(entity, resDto);
            resDto.setIsPublic(entity.getIsPublic() == 1);
            resDto.setIsUseCallphone("1".equals(entity.getIsUseCallphone()));
            resDto.setBirthday(Util.ChangeDateToString(entity.getBirthday(), BaseConstant.FORMAT_DATE_3));
        } else {
            throw new BusinessException("查询不到该用户信息，请联系管理员", ResultStatus.FAILOfficial);
        }
        return resDto;
    }

    @Transactional
    public void updateUserDepartment(UpdateUserDepartmentReqDto updateUserDepartment){

        updateUserDepartment.setEditorId(currentUserService.getUserId());
        //参数校验
        if(Util.IsNullAndEmpty(updateUserDepartment.getUserIds()) || updateUserDepartment.getDepartmentId() == null || updateUserDepartment.getIsRelieve() == null){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }
        String[] userIds = updateUserDepartment.getUserIds().split(",");

        if(userIds == null || userIds.length == 0){
            throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
        }

        if(yxDepartmentsMapper.selectByDepartmentId(updateUserDepartment.getDepartmentId()) == null){
            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        //部门关系校验
        for (String uid : userIds) {
            YxDepartmentUser ydu = new YxDepartmentUser();
            ydu.setUserId(Integer.parseInt(uid));
            ydu.setDepartmentId(updateUserDepartment.getDepartmentId());
            List<YxDepartmentUser> result = yxDepartmentUserMapper.selectByEntityList(ydu);
            if (result != null && result.size() > 0) {
                YxUsers yxUsers =  usersMapper.selectByPrimaryKey(Integer.parseInt(uid));
                if (UserType.IsRelieve.getCode() == updateUserDepartment.getIsRelieve()) {
                    /*
                    if(result.get(0).getDepartRelation() !=1){
                        throw new BusinessException(yxUsers.getTrueName()+"："+DepartmentError.ERROR_DEPARTMENT_RELATION_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);
                    }
                    */
                }else{
                    throw new BusinessException(yxUsers.getTrueName()+"："+DepartmentError.ERROR_DEPARTMENT_RELATION_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);
                }

            }
        }


        try {

            if (UserType.IsRelieve.getCode() == updateUserDepartment.getIsRelieve()) {

                for (String uid : userIds) {

                    //删除不包含调入部门的领导关系
                    YxDepartmentLeader yxDepartmentLeader = new YxDepartmentLeader();
                    yxDepartmentLeader.setUserId(Long.parseLong(uid));
                    yxDepartmentLeader.setIsDelete(1);
                    yxDepartmentLeader.setDepartmentId(updateUserDepartment.getDepartmentId());
                    yxDepartmentLeaderMapper.deleteLeaderByUserId(yxDepartmentLeader);

                    //解除之前的部门关系
                    yxDepartmentUserMapper.deleteDepartmentUserByUserId(Integer.parseInt(uid));
                }

                for (String uid : userIds) {

                    //插入用户部门
                    YxDepartmentUser yxDepartmentUser = new YxDepartmentUser();
                    yxDepartmentUser.setUserId(Integer.parseInt(uid));
                    yxDepartmentUser.setDepartmentId(updateUserDepartment.getDepartmentId());
                    yxDepartmentUser.setCreateBy(updateUserDepartment.getEditorId());
                    yxDepartmentUser.setCrmUserGroupId(0);
                    yxDepartmentUser.setDepartRelation(Byte.valueOf("0"));
                    yxDepartmentUserMapper.insertDepartmentUser(yxDepartmentUser);
                }



            } else {

                //调入虚拟部门，原部门不动
                for (String uid : userIds) {

                    //插入用户部门
                    YxDepartmentUser yxDepartmentUser = new YxDepartmentUser();
                    yxDepartmentUser.setUserId(Integer.parseInt(uid));
                    yxDepartmentUser.setDepartmentId(updateUserDepartment.getDepartmentId());
                    yxDepartmentUser.setCreateBy(updateUserDepartment.getEditorId());
                    yxDepartmentUser.setCrmUserGroupId(0);
                    //虚拟关系
                    yxDepartmentUser.setDepartRelation(Byte.valueOf("1"));
                    yxDepartmentUserMapper.insertDepartmentUser(yxDepartmentUser);
                }

            }


        }catch (Exception e){
            log.error("api/departments/updateUserDepartment", e);
            throw new BusinessException(ResultStatus.ERROR_UPDATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }


    }




    @Override
    @Transactional
    public boolean updateUser(UserUpdateReqDto parmDto){
        if(StringUtils.isNotBlank(parmDto.getEmail())) {
            //校验邮箱格式
            if(!RegexUtil.isEmail(parmDto.getEmail())){
                throw new BusinessException(DepartmentError.ERROR_EMIAL_FORMAT.getMsg(), ResultStatus.FAILOfficial);
            }
            //检查email是否占用
            YxUsers yxUsers = new YxUsers();
            yxUsers.setEmail(parmDto.getEmail());
            yxUsers.setId(parmDto.getId());
            if (usersMapper.queryUserByParam(yxUsers) != null) {
                throw new BusinessException(DepartmentError.ERROR_EMAIL_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);

            }
        }
        if(StringUtils.isNotBlank(parmDto.getMobile())) {
            //校验手机号格式
            if(!RegexUtil.isMobile(parmDto.getMobile())){
                throw new BusinessException(DepartmentError.ERROR_MOBILE_FORMAT.getMsg(), ResultStatus.FAILOfficial);
            }
            //检查手机号是否占用
            YxUsers yxUsers = new YxUsers();
            yxUsers.setMobile(parmDto.getMobile());
            yxUsers.setId(parmDto.getId());
            if (usersMapper.queryUserByParam(yxUsers) != null) {
                throw new BusinessException(DepartmentError.ERROR_MOBILE_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);

            }
        }
        if(StringUtils.isNotBlank(parmDto.getWorkNo())) {
            //检查工号是否占用
            YxUsers yxUsers = new YxUsers();
            yxUsers.setWorkNo(parmDto.getWorkNo());
            yxUsers.setId(parmDto.getId());
            if (usersMapper.queryUserByParam(yxUsers) != null) {
                throw new BusinessException(DepartmentError.ERROR_WORK_NO_IS_EXIST.getMsg(), ResultStatus.FAILOfficial);

            }
        }
        //删除用户app关联
        usersMapper.deleteUserClientRelation(parmDto.getId());
        //新增用户app关联
        if(CollectionUtils.isNotEmpty(parmDto.getAppIdList())){
            usersMapper.addUserClientRelation(parmDto);
        }
        //修改用户阿里云信息
        YxUserAliyunmq yxUserAliyunmq = new YxUserAliyunmq();
        PropertiesUtil.copyProperties(parmDto,yxUserAliyunmq);
        yxUserAliyunmq.setIsDefault(parmDto.getAliyunmqIsDefault()?1:0);
        yxUserAliyunmq.setId(parmDto.getAliyunmqId());
        yxUserAliyunmqMapper.updateUserAliyunmq(yxUserAliyunmq);
        //修改用户基础信息
        YxUsers entity = new YxUsers();
        PropertiesUtil.copyProperties(parmDto,entity);
        entity.setBirthday(Util.ChangeStringToDate(parmDto.getBirthday(),BaseConstant.FORMAT_DATE_3));
        entity.setIsPublic(parmDto.getIsPublic()?1:0);
        entity.setIsUseCallphone(parmDto.getIsUseCallphone()?"1":"0");
        return usersMapper.updateUser(entity) > 0;
    }

    @Override
    @Transactional
    public boolean deleteDepartmentUserRelation(Integer userId,Integer departmentId) {
        YxDepartments departments = departmentsMapper.selectByPrimaryKey(departmentId);
        if (departments == null) {
            throw new BusinessException("查询不到该用户部门信息，请联系管理员", ResultStatus.FAILOfficial);
        } else {
            YxDepartmentUser params = new YxDepartmentUser();
            params.setUserId(userId);
            params.setDepartmentId(departmentId);
            YxDepartmentUser entity = yxDepartmentUserMapper.queryDepartUserByParam(params);
            if ((UserConstant.USER_DEPART_VIRTUAL_RELATION == entity.getDepartRelation() && BaseConstant.CAMPUS_LEVEL_TYPE.equals(departments.getCampusLevelType()))
                    || !BaseConstant.CAMPUS_LEVEL_TYPE.equals(departments.getCampusLevelType())) {
                //第一种：是校区而且是虚拟部门；第二种：不是校区
                usersMapper.deleteDepartmentUserRelation(params);
                if (BaseConstant.IS_DELETE_FLAG_NO == departments.getIsDelete()) {
                    YxDepartments parent = getParent(departments);
                    int count = usersMapper.queryDepartUserByParam(userId, parent.getId());
                    if (count == 0) {
                        entity.setDepartmentId(parent.getId());
                        entity.setCreateBy(currentUserService.getUserId());
                        entity.setCreateTime(new Date());
                        return yxDepartmentUserMapper.insertDepartmentUser(entity) > 0;
                    }
                    return true;
                }
                return false;
            } else {
                throw new BusinessException("不能从当前部门移除", ResultStatus.FAILOfficial);
            }
        }
    }

    /**
     * 递归获取父级部门
     *
     * @param yxDepartments
     * @return
     */
    private YxDepartments getParent(YxDepartments yxDepartments) {
        YxDepartments departments = departmentsMapper.selectByEntity(new YxDepartments() {{
            setId(yxDepartments.getParentId());
            setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
        }});
        if (null != departments) {
            if (!BaseConstant.CAMPUS_LEVEL_TYPE.equals(departments.getCampusLevelType())) {
                departments = getParent(departments);
            }
        } else {
            return yxDepartments;
        }
        return departments;
    }

    @Override
    public boolean updateUserLeave(UserUpdateLeaveReqDto resDto){
        YxUsers entity = new YxUsers();
        PropertiesUtil.copyProperties(resDto,entity);
        if(UserConstant.USER_LEAVE_TYPE.equals(resDto.getOpt())){//离职
            entity.setIsLeave(UserConstant.USER_LEVEL_STATUS);
        } else if(UserConstant.USER_ONJOB_TYPE.equals(resDto.getOpt())){//入职
            entity.setIsLeave(UserConstant.USER_ONJOB_STATUS);
        } else{//暂时支持离职、入职两种操作
            return false;
        }
        return usersMapper.updateUserLeave(entity) > 0;
    }

    @Override
    public List<RolesLoginResDto> queryLoginRolesList(Integer userId){
        List<RolesLoginPojo> pojoList = new ArrayList<>();
        if(currentUserService.CheckIsSysAdmin()){
            pojoList = usersMapper.queryAdminLoginRolesList(userId);
        } else {
            pojoList = usersMapper.queryLoginRolesList(userId, currentUserService.getUserId());
        }
        List<RolesLoginResDto> resDtoList = pojoList.stream().map(pojo -> {
            RolesLoginResDto resDto = new RolesLoginResDto();
            PropertiesUtil.copyProperties(pojo,resDto);
            return resDto;
        }).collect(Collectors.toList());
        return resDtoList;
    }

    @Override
    public Map<String, Object> queryLoginNavAndFuncList(Integer userId, Integer appId){
        Map<String,Object> result = new HashMap<>();
        //查询登录用户的一级菜单
        List<NavAndFuncLoginResDto> parentList = new ArrayList<>();
        if(currentUserService.CheckIsSysAdmin()) {//超级管理员
            parentList = usersMapper.queryAdminLoginParentNavList(appId);
        } else {//普通用户
            parentList =  usersMapper.queryLoginParentNavList(currentUserService.getUserId(), appId);
        }
        if(CollectionUtils.isNotEmpty(parentList)){
            //查询登录用户非一级菜单以及功能
            List<NavAndFuncLoginResDto> allChildList = new ArrayList<>();
            if(currentUserService.CheckIsSysAdmin()){//超级管理员
                allChildList = usersMapper.queryAdminLoginAllChildNavList(appId);
            } else {
                allChildList = usersMapper.queryLoginAllChildNavList(currentUserService.getUserId(),appId);
            }
            if(CollectionUtils.isNotEmpty(allChildList)){
                for(NavAndFuncLoginResDto parent:parentList) {
                    queryChildListByParentId(parent,parent.getId(),allChildList);
                }
            }
        }

        //查询当前用户的菜单以及功能
        Set<String> checkList = usersMapper.queryUserCheckNavList(userId,appId);
        //该菜单是否展开
        Set<String> openList = new HashSet<>();
        if(CollectionUtils.isNotEmpty(parentList) && CollectionUtils.isNotEmpty(checkList)) {
            for(NavAndFuncLoginResDto parent:parentList){
                checkUpOpen(openList, parent, checkList);
            }
        }
        result.put("navAndFuncList",parentList);
        result.put("checkList",checkList);
        result.put("openList",openList);
        return result;
    }

    //根据父id查找当前子菜单
    private void queryChildListByParentId(NavAndFuncLoginResDto parent,String pid,List<NavAndFuncLoginResDto> allChildList){
        List<NavAndFuncLoginResDto> childList = new ArrayList<>();
        if(!pid.contains("-")){
            for(NavAndFuncLoginResDto child : allChildList){
                if(pid.equals(child.getPid()+"")){
                    queryChildListByParentId(child,child.getId(),allChildList);
                    childList.add(child);
                }
            }
        }
        parent.setChildList(childList);
    }

    //检查是否需要展开
    private void checkUpOpen(Set<String> openList,NavAndFuncLoginResDto parent,Set<String> checkList){
        if(!parent.getId().contains("-")) {//非功能
            if (CollectionUtils.isNotEmpty(parent.getChildList())) {//当子集合不为空
                for (NavAndFuncLoginResDto child : parent.getChildList()) {
                    if (!child.getId().contains("-")) {//非功能
                        if (checkList.contains(child.getId())) {
                            openList.add(child.getId());
                        }
                        checkUpOpen(openList, child, checkList);
                    }
                }
            }
        }
    }

    @Override
    @Transactional
    public boolean addUserRoleRelation(UserRelateRoleReqDto resDto){
        //删除用户角色关联
        usersMapper.deleteUserRoleRelation(resDto.getUserId());
        //用户关联角色
        if(CollectionUtils.isNotEmpty(resDto.getRoleIdList())) {
            return usersMapper.addUserRoleRelation(currentUserService.getUserId(), resDto) > 0;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean addUserNavigationRelation(UserRelateNavigationReqDto resDto){
        //菜单集合
        List<Integer> navList = new ArrayList<>();
        //功能集合
        List<Map<String,Integer>> navFuncMapList = new ArrayList<>();
        //删除用户菜单关联
        userNavigationsMapper.deleteUserNavRelation(resDto.getUserId());
        //删除用户菜单功能关联
        userNavigationFunctionMapper.deleteUserNavFuncRelation(resDto.getUserId());
        List<String> navAndFuncList = resDto.getNavAndFuncList();
        if(CollectionUtils.isNotEmpty(navAndFuncList)) {
            for (String str : navAndFuncList) {
                if (str.contains("-")) {
                    Map<String, Integer> navFuncMap = new HashMap<>();
                    String[] strArr = str.split("-");
                    navFuncMap.put("functionId", Integer.valueOf(strArr[0]));
                    navFuncMap.put("navigationId", Integer.valueOf(strArr[1]));
                    navFuncMapList.add(navFuncMap);
                } else {
                    navList.add(Integer.valueOf(str));
                }
            }
        }
        Map<String,Object> params = new HashMap<>();
        params.put("loginId",currentUserService.getUserId());
        params.put("userId",resDto.getUserId());
        if(navList.size() > 0){
            //新增用户菜单关联
            params.put("navList",navList);
            usersMapper.addUserNavigationRelation(params);
        }
        if(navFuncMapList.size() > 0){
            params.put("navFuncMapList",navFuncMapList);
            //新增用户菜单功能关联
            usersMapper.addUserNavFuncRelation(params);
        }
        return true;
    }

    @Override
    public boolean resetPwd(Integer id){
        //根据id获取用户信息
        YxUsers entity = usersMapper.queryUserById(id);
        if(entity == null){
            throw new BusinessException("用户不存在", ResultStatus.EXCEPTION);
        }
        //默认密码“123456”
        String password = UserConstant.DEFAULT_PASSWORD;
        String mobile = entity.getMobile();
        //若用户手机号不为空，则取手机号后6位
        if(StringUtils.isNotEmpty(mobile)){
            password = mobile.substring(mobile.length() - 6);
        }
        //MD5加密后截取20位
        entity.setPassword(EncryptUtil.md5(password).substring(0,20));
        entity.setUpdatePwdDate(new Date());
        return usersMapper.resetPwd(entity) > 0;
    }

    /**
     * 根据主键查询用户信息
     * @param id
     * @return
     */
    @Override
    public YxUsers selectByPrimaryKey(Integer id) {
        return usersMapper.selectByPrimaryKey(id);
    }


    @Override
    public boolean updateByPrimaryKeySelective(YxUsers yxUsers){
        return usersMapper.updateByPrimaryKeySelective(yxUsers) > 0 ;
    }

    @Override
    public Map<String, Object> queryLoginHomePageList(Integer userId, Integer appId){
        Map<String,Object> result = new HashMap<>();
        List<NavigationListResDto> navList = navigationsService.queryLoginNavigationList(appId);
        YxHomepageConfig yxHomepageConfig = usersMapper.queryHomePageByUserId(userId,appId);
        result.put("navList",navList);
        result.put("check",yxHomepageConfig);
        return result;
    }

    @Override
    @Transactional
    public boolean addHomePage(HomepageConfigReqDto parmDto){
        YxHomepageConfig entity = new YxHomepageConfig();
        PropertiesUtil.copyProperties(parmDto,entity);
        entity.setCreateBy(currentUserService.getUserId());
        entity.setType(UserConstant.HOME_PAGE_TYPE_USER);
        usersMapper.deleteHomePage(entity);
        return usersMapper.addHomePage(entity) > 0;
    }

    @Override
    public YxUsers getUserInfoByUsername(Integer integer,String username) {
            Example example=new Example(YxUsers.class);
            Example.Criteria criteria = example.createCriteria();
            YxUsers userDto=new YxUsers();
            List<YxUsers> users=new ArrayList<>();
            if (1 == integer) {//电话
                criteria.andEqualTo("mobile", username);
                users = usersExampleMapper.selectByExample(example);
                if (users.size() > 0) {
                    userDto = users.get(0);

                }
            } else if (2 == integer) {//email
                criteria.andEqualTo("email", username);
                users = usersExampleMapper.selectByExample(example);
                if (users.size() > 0) {
                    userDto = users.get(0);
                }
            }else{
                criteria.andEqualTo("userName", username);
                users = usersExampleMapper.selectByExample(example);
                if (users.size() > 0) {
                    userDto = users.get(0);
                }
            }

            return userDto;
        }
    //根据用户名查询当前用户（提供给CRM项目，非手机号即用户名）
    @Override
    public YxUsers getCurrentUser(Integer type, String username) {
        YxUsers yxUsers=null;
        Example example=new Example(YxUsers.class);
        Example.Criteria criteria = example.createCriteria();
        List<YxUsers> users=new ArrayList<>();
        if(1==type){
            criteria.andEqualTo("mobile", username);
            users = usersExampleMapper.selectByExample(example);
            if (users.size() > 0) {
                yxUsers = users.get(0);
            }
        }else{
            criteria.andEqualTo("userName", username);
            users = usersExampleMapper.selectByExample(example);
            if (users.size() > 0) {
                yxUsers = users.get(0);
            }

        }
        return yxUsers;
    }

    @Override
    public UserHasPermissionPojo getUserPermissionInfo(Integer flag, String username) {
        UserHasPermissionPojo userPermisson=null;
        if (1 == flag) {//电话
            userPermisson= usersMapper.getUserPermissionInfoByMobile(username);
        } else if (2 == flag) {//email
            userPermisson= usersMapper.getUserPermissionInfoByEmail(username);
        } else {
            return userPermisson;
        }

        return userPermisson;
    }

    @Override
    public List<UserBaseInfoDto> getUsersByIds(List<Integer> userIds) {
        List<UserBaseInfoDto> retList = new ArrayList<>();
        if (userIds == null || userIds.size() == 0) {
            return retList;
        }
        Example example = new Example(YxUsers.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", userIds);
        List<YxUsers> users = usersExampleMapper.selectByExample(example);
        if(users!=null&&users.size()>0){
            for (YxUsers u:users){
                UserBaseInfoDto userBaseInfoDto=new UserBaseInfoDto();
                PropertiesUtil.copyProperties(u,userBaseInfoDto);
                userBaseInfoDto.setUser_id(u.getId());
                retList.add(userBaseInfoDto);
            }
        }
        return retList;
    }

    @Override
    public List<UserBaseInfoDto> getUsersByCampusId(Integer campusId,Boolean isAll) {
        List<UserBaseInfoDto> retList = new ArrayList<>();
        if (campusId == null || campusId <= 0) {
            return retList;
        }
        if(isAll==null){
            isAll=false;
        }
        Example example = new Example(YxUsers.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("campusId",campusId);
        if(!isAll){
            criteria.andEqualTo("isLeave",0);
            criteria.andEqualTo("isDelete",0);
        }
        List<YxUsers> users= usersExampleMapper.selectByExample(example);
        if(users!=null&&users.size()>0){
            for(YxUsers u:users){
                UserBaseInfoDto userBaseInfoDto=new UserBaseInfoDto();
                PropertiesUtil.copyProperties(u,userBaseInfoDto);
                userBaseInfoDto.setUser_id(u.getId());
                userBaseInfoDto.setTrue_name(u.getTrueName());
                retList.add(userBaseInfoDto);
            }
        }
        return retList;
    }

    @Override
    public QueryResponse<QueryPageRes<List<AccountPageLIstResDto>>> selectByMobileOrName(String account, Integer status, int pageIndex,int pageSize) {
        YxUsers userBaseInfo = currentUserService.getUserBaseInfo();
        Page<List<YxUsers>> page = PageHelper.startPage(pageIndex, pageSize);
        List<AccountPageLIstResDto> yxUsers = usersMapper.selectByMobileOrName(PositionEnum.SchoolMaster.getCode(), account, status, userBaseInfo.getCampusId());
        return QueryPageRes.setQueryResponseData(yxUsers,page.getTotal());
    }


    @Override
    @Transactional
    public QueryResponse addUser(UserAddReqDto userInfo) {
        Date date = new Date();
        YxUsers currentUser = currentUserService.getUserBaseInfo();

        YxUsers yxUsers1 = usersMapper.selectByEntity(new YxUsers() {{
            setUserName(userInfo.getUserName());
            setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
        }});
        if (null != yxUsers1){
            return new QueryResponse(ResultStatus.ERROR_IS_EXIST.getErrorCode(),"该用户名已被使用");
        }
        YxUsers yxUsers2 = usersMapper.selectByEntity(new YxUsers() {{
            setMobile(userInfo.getMobile());
            setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
        }});
        if (null != yxUsers2){
            return new QueryResponse(ResultStatus.ERROR_IS_EXIST.getErrorCode(),"该手机号已被使用");
        }

        YxUsers yxUsers = new YxUsers() {{
            setMobile(userInfo.getMobile());
            setUserName(userInfo.getUserName());
            setTrueName(userInfo.getTrueName());
            setPassword(EncryptUtil.md5(userInfo.getPassword()).substring(0, 20).toUpperCase());
            setRemark(userInfo.getRemark());
            setCreateTime(date);
            setCreateBy(currentUser.getId());
            setSchoolId(currentUser.getSchoolId());
            setCampusId(currentUser.getCampusId());
        }};
        usersMapper.insertSelective(yxUsers);
        //插入菜单以及权限
        List<NavigationReqDto> navigations = userInfo.getNavigations();
        addNavigationAndFunction(navigations,yxUsers.getId());
        return new QueryResponse();
    }

    /**
     * 新增用户菜单以及权限
     * @param navigations
     * @param userId
     */
    private void addNavigationAndFunction(List<NavigationReqDto> navigations,Integer userId){
        List<Integer> navIds = new ArrayList<>();//菜单集合
        List<Map<String,Integer>> navFuncMapList = new ArrayList<>();//权限集合
        for (NavigationReqDto navigation : navigations) {
            Integer navigationId = navigation.getNavId();
            navIds.add(navigationId);
            for (Integer functionId : navigation.getFunctionIds()) {
                Map<String,Integer> map = new HashMap<>();
                map.put("navigationId",navigationId);
                map.put("functionId",functionId);
                navFuncMapList.add(map);
            }
        }
        Map<String,Object> params = new HashMap<>();
        params.put("loginId",currentUserService.getUserId());
        params.put("userId",userId);
        if(navIds.size()>0){//添加用户菜单关联
            params.put("navList",navIds);
            usersMapper.addUserNavigationRelation(params);
        }
        if(navFuncMapList.size()>0){
            params.put("navFuncMapList",navFuncMapList);
            //新增用户菜单功能关联
            usersMapper.addUserNavFuncRelation(params);
        }
    }


    /**
     * 根据id查询用户详情
     * @param id
     * @return
     */
    @Override
    public AccountInfoResDto selectUserById(Integer id) {
        AccountInfoResDto resDto = usersMapper.selectUserById(id);
        if (null != resDto){
            //查询菜单集合
            List<YxUserNavigations> yxUserNavigations = userNavigationsMapper.selectByUserId(id);
            //查询功能集合
            List<YxUserNavigationFunction> yxUserNavigationFunctions = userNavigationFunctionMapper.queryByUserId(id);
            if (CollectionUtils.isNotEmpty(yxUserNavigations)){
                List<Integer> NavigationIds = yxUserNavigations.stream().map(x -> x.getNavigationId()).distinct().collect(Collectors.toList());
                List<NavAndFuncByRoleResDto> navIds = new ArrayList<>();
                for (Integer navigationId : NavigationIds) {
                    NavAndFuncByRoleResDto roleResDto = new NavAndFuncByRoleResDto();
                    roleResDto.setNavigationId(navigationId);
                    if (CollectionUtils.isNotEmpty(yxUserNavigationFunctions)){
                        List<Integer> functionIds = yxUserNavigationFunctions.stream().filter(a -> navigationId.equals(a.getNavigationId())).map(x -> x.getFunctionId()).collect(Collectors.toList());
                        roleResDto.setFunctionIds(functionIds);
                    }
                    navIds.add(roleResDto);
                }
                resDto.setNavIds(navIds);
            }
        }
        return resDto;
    }

    @Override
    @Transactional
    public boolean updateUser(UserInfoUpdateReqDto requset) {
        //更新用户信息
        usersMapper.updateByPrimaryKeySelective(new YxUsers() {{
            setId(requset.getId());
            setRemark(requset.getRemark());
        }});

        //删除用户角色关联(校长初始化的时候会有角色)
        usersMapper.deleteUserRoleRelation(requset.getId());
        //删除用户菜单关联
        userNavigationsMapper.deleteUserNavRelation(requset.getId());
        //删除用户菜单功能关联
        userNavigationFunctionMapper.deleteUserNavFuncRelation(requset.getId());

        //新增用户菜单以及权限
        addNavigationAndFunction(requset.getNavIds(),requset.getId());

        return true;
    }

    //根据多个id查询用户信息
    @Override
    public List<AccountInfoListResDto> queryUserInfoByIds(List<Integer> userIds){
        List<AccountInfoListResDto> resDtoList = usersMapper.queryUserInfoByIds(userIds);
        return resDtoList;
    }

    //根据校区查询出非userId的用户信息
    @Override
    public List<AccountInfoListResDto> queryUserInfoListByCampusId(Integer userId,Integer campusId){
        List<AccountInfoListResDto> resDtoList = usersMapper.queryUserInfoListByCampusId(userId,campusId);
        return resDtoList;
    }

    //根据真实姓名模糊查询用户信息
    @Override
    public List<AccountInfoListResDto> queryUserInfoListByTrueName(String trueName,Integer campusId){
        List<AccountInfoListResDto> resDtoList = usersMapper.queryUserInfoListByTrueName(trueName,campusId);
        return resDtoList;
    }
}


